<template>
  <div class="shop-register-container">
    <el-card class="register-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">注册成为店铺</h1>
          <p class="subtitle">完善您的店铺信息，审核通过后即可购买和使用剧本</p>
        </div>
      </template>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        label-width="100px"
        @submit.prevent="handleRegister"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="请输入店铺名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入联系电话"
            maxlength="11"
            clearable
          />
        </el-form-item>

        <el-form-item label="邮箱地址" prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="店铺地址" prop="address">
          <el-input
            v-model="registerForm.address"
            placeholder="请输入店铺地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="营业执照" prop="licenseFile">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="1"
            accept="image/*,.pdf"
            list-type="picture-card"
          >
            <template #default>
              <el-icon><Plus /></el-icon>
            </template>
            <template #tip>
              <div class="upload-tip">
                支持上传图片或PDF文件，大小不超过5MB（建议上传）
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="loading"
            class="submit-btn"
          >
            {{ loading ? '提交中...' : '提交申请' }}
          </el-button>
          <el-button @click="handleCancel">
            取消
          </el-button>
        </el-form-item>
      </el-form>

      <div class="info-box">
        <el-alert
          title="温馨提示"
          type="info"
          :closable="false"
          show-icon
        >
          <template #default>
            <ul class="info-list">
              <li>提交申请后，我们会在1-3个工作日内完成审核</li>
              <li>请确保提供的信息真实有效，特别是店铺地址</li>
              <li>建议上传营业执照，营业执照需清晰可见，确保关键信息完整</li>
              <li>如未上传营业执照，可稍后在个人中心补充上传</li>
              <li>审核结果将通过邮箱通知您</li>
            </ul>
          </template>
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import {type FormInstance, type FormRules, type UploadFile, type UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { addShopAPI, uploadShopLicenseAPI } from '@/api/shop'

const router = useRouter()
const userStore = useUserStore()

const registerFormRef = ref<FormInstance>()
const uploadRef = ref()
const loading = ref(false)
const fileList = ref<UploadUserFile[]>([])
const currentFile = ref<File | null>(null)

const registerForm = reactive({
  name: '',
  phone: '',
  email: '',
  address: '',
  licenseFile: ''
})

// 电话号码验证
const validatePhone = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!value) {
    callback(new Error('请输入联系电话'))
  } else if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

// 邮箱验证
const validateEmail = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  const emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!value) {
    callback(new Error('请输入邮箱地址'))
  } else if (!emailReg.test(value)) {
    callback(new Error('请输入正确的邮箱地址'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 50, message: '店铺名称长度在2到50个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, validator: validateEmail, trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入店铺地址', trigger: 'blur' },
    { min: 5, max: 100, message: '店铺地址长度在5到100个字符', trigger: 'blur' }
  ]
})

// 文件变化处理
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return

  // 验证文件大小
  const isLt5M = file.size! / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB')
    fileList.value = []
    currentFile.value = null
    return
  }

  // 验证文件类型
  const isValidType = file.raw.type.startsWith('image/') || file.raw.type === 'application/pdf'
  if (!isValidType) {
    ElMessage.error('只能上传图片或PDF文件')
    fileList.value = []
    currentFile.value = null
    return
  }

  currentFile.value = file.raw
}

// 文件移除处理
const handleFileRemove = () => {
  currentFile.value = null
  registerForm.licenseFile = ''
  fileList.value = []
}

// 上传营业执照
const uploadLicense = async (shopId: number): Promise<string> => {
  if (!currentFile.value) {
    throw new Error('没有选择文件')
  }

  try {
    const { data: res } = await uploadShopLicenseAPI(currentFile.value, shopId)
    if (res.code === 1) {
      return res.data // 返回文件路径
    } else {
      throw new Error(res.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传营业执照失败', error)
    throw error
  }
}

// 提交注册
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    loading.value = true

    // 获取当前用户ID作为店铺ID
    const userId = (userStore.userInfo as { id: number }).id

    // 创建店铺记录（licenseFile暂时为空）
    const { data: res } = await addShopAPI({
      name: registerForm.name,
      phone: registerForm.phone,
      email: registerForm.email,
      address: registerForm.address,
      licenseFile: '' // 先提交空字符串
    })

    if (res.code !== 1) {
      ElMessage.error(res.msg || '提交失败，请重试')
      loading.value = false
      return
    }

    // 如果有上传文件，则上传营业执照
    if (currentFile.value) {
      try {
        await uploadLicense(userId)
        ElMessage.success('申请提交成功！营业执照已上传，请等待审核')
      } catch {
        ElMessage.warning('店铺信息已提交，但营业执照上传失败，请稍后在个人中心重新上传')
      }
    } else {
      ElMessage.success('申请提交成功！请等待审核')
    }

    // 跳转回店铺剧本管理页面
    setTimeout(() => {
      router.push('/content/script/shop')
    }, 1500)

  } catch (err) {
    console.error('注册失败', err)
    ElMessage.error('提交失败，请重试')
  } finally {
    loading.value = false
  }
}

// 取消注册
const handleCancel = () => {
  router.back()
}
</script>

<style scoped>
.shop-register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  padding: 2rem 1rem;
}

.register-card {
  width: 100%;
  max-width: 600px;
}

.card-header {
  text-align: center;
}

.title {
  font-size: 1.75rem;
  font-weight: 500;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.subtitle {
  font-size: 0.875rem;
  color: #666;
  margin: 0;
}

.upload-demo {
  width: 100%;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.submit-btn {
  margin-right: 12px;
}

.info-box {
  margin-top: 20px;
}

.info-list {
  margin: 0;
  padding-left: 20px;
  font-size: 14px;
  line-height: 1.8;
}

.info-list li {
  margin: 4px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shop-register-container {
    padding: 1rem 0.75rem;
  }

  .register-card {
    max-width: 100%;
  }

  .title {
    font-size: 1.5rem;
  }

  :deep(.el-form-item__label) {
    width: 80px !important;
  }
}

@media (max-width: 480px) {
  .shop-register-container {
    padding: 0.5rem;
  }

  .title {
    font-size: 1.25rem;
  }

  :deep(.el-form-item__label) {
    width: 70px !important;
  }
}
</style>

